import {createContext, useContext, useReducer,useState} from "react";

const DemoStateContext = createContext(null)
const DemoDispatch = createContext(null)

// 创建reducer
const reducer = (state, action) => {
    switch (action.type) {
        case 'add_something':
            return [
                ...state,
                {name:action.info,id:Math.floor(Math.random()*90000)+10000,age:Math.floor(Math.random()*90)+10}
            ]
        case 'delete_something':
            return state.filter(item => item.id != action.id)
        default :
            return new Error(`未知状态: ${action.type}`)
    }
}

// 初始化数据源
const initData = [
    {id:1,name: 'Jack', age: 18}
]

// App组件
const AddUserComponent = () => {
    const [state, dispatch] = useReducer(reducer,initData)
    return (
        <DemoDispatch.Provider value={dispatch}>
            <DemoStateContext.Provider value={state}>
                <AddUserHeader/>
                <AddUserBody />
            </DemoStateContext.Provider>
        </DemoDispatch.Provider>
    )
}

const AddUserHeader = () => {
    const dispatch = useContext(DemoDispatch)
    const [inputValue,setInputValue] = useState('')
    const onChange = (e)=> {
        setInputValue(e.target.value)
    }
    const addUser = ()=>{
        dispatch({
            type: "add_something",
            info: inputValue
        })
        setInputValue('')
    }
    return (
        <>
            <input value={inputValue} onChange={onChange}/>
            <button onClick={addUser}>添加</button>
        </>
    )
}

const AddUserBody = () => {
    const userInfo = useContext(DemoStateContext)
    const userlis= userInfo.map(item=>{
        return <AddUserLi data={item} key={item.id}/>
    })
    return (
        <>
            {userlis}
        </>
    )
}

const AddUserLi = ({data}) => {
    const dispatch = useContext(DemoDispatch)
    const delUser = ()=>{
        dispatch({
            type:'delete_something',
            id:data.id
        })
    }
    return (
        <div>
            名字: {data.name},年龄: {data.age}
            <button onClick={delUser}>删除</button>
        </div>
    )
}

export default AddUserComponent